package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
)

type DicDataController struct {
}

func DicDataRegister(group *gin.RouterGroup) {
	dicData := &DicDataController{}
	//字典表新增
	group.POST("/add", dicData.Add)
	//根据键值查询字典
	group.GET("/get_dic_data", dicData.GetDataByKey)
	group.GET("/dic_data/data", dicData.Data)
}
func (d *DicDataController) Data(c *gin.Context) {
	middleware.ResponseSuccess(c, map[string]interface{}{
		"categories": []string{"1", "2"},
		"series": []map[string]interface{}{
			{
				"data": []int64{
					1000879,
					3400879,
					2300879,
					5400879,
					3400879,
				},
			},
		},
	}, true)
}
func (d *DicDataController) Add(c *gin.Context) {
	params := &dto.DicDataAddInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	dicData := &dao.DicData{
		Pid:   params.Pid,
		Key:   params.Key,
		Label: params.Label,
		Value: params.Value,
	}
	if err := dicData.Save(c, tx); err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (d *DicDataController) GetDataByKey(c *gin.Context) {
	params := &dto.GetDataByKeyInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}

	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败,请稍后重试"), true)
		return
	}
	var dic []dao.DicData
	if result := tx.Model(&dao.DicData{}).Where(map[string]interface{}{
		"status":    0,
		"is_delete": 0,
	}).Where(&dao.DicData{
		Key: params.Key,
	}).Where("pid <> ?", "").Find(&dic); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("获取数据失败,请稍后重试"), true)
		return
	}
	var out []dto.DicDataInfo
	for _, item := range dic {
		out = append(out, dto.DicDataInfo{
			Id:    fmt.Sprintf("%d", item.Id),
			Key:   item.Key,
			Label: item.Label,
			Value: item.Value,
		})
	}
	middleware.ResponseSuccess(c, out, true)
}
